package com.clss.commandhelper.function.home;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.clss.commandhelper.R;
import com.clss.commandhelper.base.BaseActivity;
import com.clss.commandhelper.function.homefragment1st.Home1stFragment;
import com.clss.commandhelper.function.homefragment2nd.Home2ndFragment;
import com.clss.commandhelper.function.homefragment3rd.Home3rdFragment;
import com.clss.commandhelper.function.homefragment4th.Home4thFragment;
import com.clss.commandhelper.function.login.LoginActivity;
import com.clss.commandhelper.function.newEvidence.EvidenceAndNewCaseActivity;
import com.clss.commandhelper.net.ApiConstants;
import com.clss.commandhelper.tools.ActivityTracker;
import com.clss.commandhelper.tools.Constant;
import com.clss.commandhelper.tools.SpHelper;
import com.clss.commandhelper.tools.Utils;
import com.clss.commandhelper.tools.VersionUpdataHelper;
import com.clss.commandhelper.tools.eventbus.EventBusHelper;
import com.clss.commandhelper.tools.eventbus.EventBusMessage;

import java.util.List;

/**
 * @author liuv
 */
public class HomeActivity extends BaseActivity implements HomePresenter.HomeView, View.OnClickListener,
        RadioGroup.OnCheckedChangeListener{
    private static final String TAG = "HomeActivity";

    private static final int HOME_FRAGMENT_1ST = 0;
    private static final int HOME_FRAGMENT_2ND = 1;
    private static final int HOME_FRAGMENT_3RD = 2;
    private static final int HOME_FRAGMENT_4TH = 3;

    private HomePresenter mHomePresenter;
    private ImageView mTopBarLeftIv;
    private ImageView mTopBarRightIv;
    private DrawerLayout mHomeDl;
    private TextView mTitleTv, mVersionTv, mExitTv, mCheckVersionTv, mCurrentUserTv;
    private RadioGroup mHomeRg;
    private RadioButton mHome1stRb, mHome2ndRb, mHome3rdRb, mHome4thRb;
    private FrameLayout mHomeFl;
    private int mCurrentFragmentPosition = HOME_FRAGMENT_4TH;
    private Home1stFragment mHome1stFragment;
    private Home2ndFragment mHome2ndFragment;
    private Home3rdFragment mHome3rdFragment;
    private Home4thFragment mHome4thFragment;

    @Override
    protected int setViewId() {
        return R.layout.activity_home;
    }

    @Override
    protected void initView() {
        mTitleTv = findViewById(R.id.include_top_bar_title_tv);
        mTopBarLeftIv = findViewById(R.id.include_top_bar_left_iv);
        mTopBarRightIv = findViewById(R.id.include_top_bar_right_iv);
        mHomeDl = findViewById(R.id.home_drawer_layout);

        mVersionTv = findViewById(R.id.home_drawer_version_tv);
        mCheckVersionTv = findViewById(R.id.home_check_new_version_tv);
        mExitTv = findViewById(R.id.home_logout_tv);
        mCurrentUserTv = findViewById(R.id.home_drawer_current_user_tv);

        mHomeFl = findViewById(R.id.home_fl);
        mHomeRg = findViewById(R.id.home_rg);
        mHome1stRb = findViewById(R.id.home_rg_1st_rb);
        mHome2ndRb = findViewById(R.id.home_rg_2nd_rb);
        mHome3rdRb = findViewById(R.id.home_rg_3rd_rb);
        mHome4thRb = findViewById(R.id.home_rg_4th_rb);

        mHomeRg.setOnCheckedChangeListener(this);

        mTitleTv.setText(getString(R.string.app_name));

        mTopBarLeftIv.setImageResource(R.mipmap.btn_menu);
        mTopBarRightIv.setImageResource(R.mipmap.icon_add);
        mTopBarRightIv.setVisibility(View.VISIBLE);
        mTopBarLeftIv.setOnClickListener(this);
        mTopBarRightIv.setOnClickListener(this);
        mCheckVersionTv.setOnClickListener(this);
        mExitTv.setOnClickListener(this);
        mVersionTv.setOnLongClickListener(v -> {
            showShortToast("版本号：" + Utils.getVersionCode() + "__" + ApiConstants.API_NAME);
            return true;
        });

        mHomePresenter = new HomePresenter();
        mHomePresenter.setHomeView(this);

        initLocation(null);

        mHomePresenter.checkVersion(false);

        mCurrentUserTv.setText(SpHelper.getInstance().getName());
        mVersionTv.setText("当前版本是：" + Utils.getVersionName());

        mHomeRg.setVisibility(View.GONE);
//        mCurrentFragmentPosition = HOME_FRAGMENT_1ST;
//        mHome4thRb.setVisibility(View.GONE);
    }

    @Override
    protected void initData(@Nullable Bundle savedInstanceState) {
        switchFragment();
    }

    @Override
    public void onBackPressed() {
        if (mHomeDl.isDrawerOpen(Gravity.LEFT)){
            mHomeDl.closeDrawers();
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void onEventMainThread(EventBusMessage eventBusMessage) {
        super.onEventMainThread(eventBusMessage);
        if (eventBusMessage.getCode() == EventBusHelper.LOCATION_SUCCESS){
            UploadLocationService.startUploadLocation(this);
        }
    }

    @Override
    public void requestFailure(Throwable t) {
        super.requestFailure(t);
    }

    @Override
    public void responseError(int code, String msg) {
        showShortToast(msg);
    }

    @Override
    public void hasNewVersion(String url, boolean canCancel) {
        SpHelper.getInstance().setLastVersionCheckTime(canCancel ? System.currentTimeMillis() : 0);
        if (checkPermission(Constant.sPermissionsArray[4], Constant.sPermissionsArray[5])){
            new VersionUpdataHelper(this, url, canCancel);
        }else {
            showLongToast(getString(R.string.storage_permission_not_has_tip));
            requestPermission();
        }
    }

    @Override
    public void isLastVersion(boolean isNeedTip){
        if (isNeedTip){
            showShortToast(getString(R.string.is_last_version));
        }
    }

    public void showLogoutDialog(){
        showInteractionDialog(getString(R.string.do_you_want_exit), (dialog, which) -> {
            dialog.dismiss();
            SpHelper.getInstance().clearAll();
            Utils.startActivity(HomeActivity.this, LoginActivity.class, null, true);
            ActivityTracker.finishAll();
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.include_top_bar_left_iv:
                mHomeDl.openDrawer(Gravity.LEFT);
                break;
            case R.id.include_top_bar_right_iv:
                Bundle bundle = new Bundle();
                bundle.putInt("type",1);
                Utils.startActivity(this, EvidenceAndNewCaseActivity.class,bundle);
                break;
            case R.id.home_check_new_version_tv:
                mHomePresenter.checkVersion(true);
                break;
            case R.id.home_logout_tv:
                showLogoutDialog();
                break;
            default:
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i){
            case R.id.home_rg_1st_rb:
                mCurrentFragmentPosition = HOME_FRAGMENT_1ST;
                break;
            case R.id.home_rg_2nd_rb:
                mCurrentFragmentPosition = HOME_FRAGMENT_2ND;
                break;
            case R.id.home_rg_3rd_rb:
                mCurrentFragmentPosition = HOME_FRAGMENT_3RD;
                break;
            case R.id.home_rg_4th_rb:
                mCurrentFragmentPosition = HOME_FRAGMENT_4TH;
                break;
            default:
        }
        switchFragment();
    }

    private void switchFragment() {
        mTopBarRightIv.setVisibility(mCurrentFragmentPosition == HOME_FRAGMENT_4TH ? View.VISIBLE : View.GONE);
        checkRadioGroup();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        switch (mCurrentFragmentPosition) {
            case HOME_FRAGMENT_1ST:
                if (mHome1stFragment == null) {
                    mHome1stFragment = new Home1stFragment();
                    mHome1stFragment.setActivity(this);
                    transaction.add(R.id.home_fl, mHome1stFragment);
                }
                hideOtherFragment(transaction, mHome1stFragment);
                transaction.show(mHome1stFragment);
                transaction.commit();
                break;
            case HOME_FRAGMENT_2ND:
                if (mHome2ndFragment == null) {
                    mHome2ndFragment = new Home2ndFragment();
                    transaction.add(R.id.home_fl, mHome2ndFragment);
                }
                hideOtherFragment(transaction, mHome2ndFragment);
                transaction.show(mHome2ndFragment);
                transaction.commit();
                break;
            case HOME_FRAGMENT_3RD:
                if (mHome3rdFragment == null) {
                    mHome3rdFragment = new Home3rdFragment();
                    transaction.add(R.id.home_fl, mHome3rdFragment);
                }
                hideOtherFragment(transaction, mHome3rdFragment);
                transaction.show(mHome3rdFragment);
                transaction.commit();
                break;
            case HOME_FRAGMENT_4TH:
                if (mHome4thFragment == null) {
                    mHome4thFragment = new Home4thFragment();
                    transaction.add(R.id.home_fl, mHome4thFragment);
                }
                hideOtherFragment(transaction, mHome4thFragment);
                transaction.show(mHome4thFragment);
                transaction.commit();
                break;
            default:
                break;
        }
    }

    private void hideOtherFragment(FragmentTransaction transaction, Fragment curFragment) {
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (fragments == null) {
            return;
        }
        for (Fragment fragment : fragments) {
            if (fragment == curFragment) {
                continue;
            }
            transaction.hide(fragment);
        }
    }

    private void checkRadioGroup(){
        if (mHomeRg.getChildAt(mCurrentFragmentPosition).getId() != mHomeRg.getCheckedRadioButtonId()){
            mHomeRg.check(mHomeRg.getChildAt(mCurrentFragmentPosition).getId());
        }
    }
}
